from django.shortcuts import render

from .serializers import *
from . import tasks as TASKS
from PlaceManager.tasks import has_pid_from_idcode
# from .PulsarSDK import SendAsyncMessage
import logging

logger = logging.getLogger(__name__)
# Create your views here.


class ThisFsygWorksGroupListViewSet(viewsets.ModelViewSet):
    __title__ = "请求场所终端分组列表"
    __group__ = "凡商接口"
    __info__ = {"post": "请求场所终端分组列表"}
    __doc__ = """
    create:
    <h4>请求场所终端分组列表</h4>
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = FsygWorksGroupSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        wbid = serializer.data.get("wb_id")
        # logger.info(f"[{wbid}] [] 收到请求 查询终端列表")
        r = TASKS.doRequestRate.apply_async((wbid,))
        return Response({"rescode": 200, "resmsg": r.task_id})


class ThisFsygAlertViewSet(viewsets.ModelViewSet):
    __title__ = "请求消息推送"
    __group__ = "凡商接口"
    __info__ = {"post": "请求消息推送"}
    __doc__ = """
    create:
    <h4>请求消息推送</h4>
        发送 2.1-3.2 接口请求
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = FsygAlertSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # serializer.save()
        if serializer.data.get("act") == "上机信息":
            r = TASKS.doRequestProgress.apply_async(
                (serializer.data.get("wb_id"), serializer.data.get("id_card_hash"))
            )
        elif serializer.data.get("act") == "用户信息":
            r = TASKS.doRequestUser.apply_async(
                (serializer.data.get("wb_id"), serializer.data.get("id_card_hash"))
            )
        elif serializer.data.get("act") == "区域/费率信息":
            r = TASKS.doRequestRate.apply_async(
                (serializer.data.get("wb_id"), serializer.data.get("id_card_hash"))
            )
        elif serializer.data.get("act") == "计费消费记录":
            r = TASKS.doRequestRecord.apply_async(
                (
                    serializer.data.get("wb_id"),
                    serializer.data.get("id_card_hash"),
                    serializer.data.get("start_time"),
                    serializer.data.get("end_time"),
                )
            )
        elif serializer.data.get("act") == "商品订单查询":
            r = TASKS.doRequestOrder.apply_async(
                (
                    serializer.data.get("wb_id"),
                    serializer.data.get("id_card_hash"),
                    serializer.data.get("start_time"),
                    serializer.data.get("end_time"),
                    serializer.data.get("page"),
                )
            )
        elif serializer.data.get("act") == "商品退单查询":
            r = TASKS.doRequestRefunds.apply_async(
                (
                    serializer.data.get("wb_id"),
                    serializer.data.get("id_card_hash"),
                    serializer.data.get("start_time"),
                    serializer.data.get("end_time"),
                    serializer.data.get("page"),
                )
            )
        else:
            raise serializers.ValidationError("act 参数错误")
        return Response({"rescode": 200, "resmsg": r.task_id})


class ThisFsygDataRecvSendViewSet(viewsets.ModelViewSet):
    __title__ = "凡商触发推送消息"
    __group__ = "凡商接口"
    __info__ = {"post": "创建触发推送消息"}
    __doc__ = """
    create:
    <h4>创建触发推送消息</h4>
        接收 1.1-2.4 接口消息
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = ThisFsygDataRecvSendSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 创建数据
        data = serializer.data.copy()
        # 去除None
        data = REDIS.clear_dict(data)        
        # 保存数据
        logger.debug(f'[fsyg] [{data.get("message_type")}] {data}')       
         
        if data.get("message_type") == "machine_change":  # 新1.6换机信息推送
            # print("换机推送")
            r = TASKS.DoChangeWorkMessage.apply_async((data,))
            return Response({"rescode": 200, "resmsg": r.task_id})            
        
        # 检测场所,编码转换
        pid = has_pid_from_idcode("凡商编码", data.get("wb_id"))
        try:
            place = AllinpayPlaceList.objects.get(status=1, id=pid)
        except Exception as err:
            raise serializers.ValidationError("该场所未注册")

        # 分类处理数据
        if data.get("message_type") == "user_info":  # 2.1.上机信息
            # print("上机信息")
            r = TASKS.doOnlineInfoList.apply_async((place.id, data))
            return Response({"rescode": 200, "resmsg": r.task_id})
        elif data.get("message_type") == "query_member":  # 2.2.用户信息
            # print("用户信息")
            r = TASKS.doMemberInfoList.apply_async((place.id, data))
            return Response({"rescode": 200, "resmsg": r.task_id})
        elif data.get("message_type") == "query_rate":  # 2.3.区域/费率信息
            # print("费率信息")
            r = TASKS.doGroupWorkList.apply_async((place.id, data))
            return Response({"rescode": 200, "resmsg": r.task_id})
        elif data.get("message_type") == "consumed_record":  # 2.4.计费消费记录
            # print("消费记录信息")
            r = TASKS.doBuyRecordsList.apply_async((place.id, data))
            return Response({"rescode": 200, "resmsg": r.task_id})
        elif data.get("message_type") in ["order", "refund"]:  # 1.3.商品订单、1.4.退单推送
            # print("订退单推送")
            r = TASKS.doShopreqsnList.apply_async((place.id, data))
            return Response({"rescode": 200, "resmsg": r.task_id})
        elif data.get("message_type") in [
            "machine_up",
            "machine_down",
        ]:  # 1.1.上机推送 # 1.2.下机推送
            if data.get("flag") == 0:
                return Response({"rescode": 200, "resmsg": "取消激活记录"})
            # print("上下机推送")
            # r = TASKS.doProgrunList.apply_async((place.id, data))
            r = TASKS.NewdoProgrunList.apply_async((place.id, data))
            return Response({"rescode": 200, "resmsg": r.task_id})
        elif data.get("message_type") == "staff_save":  # 新1.3员工信息推送
            # print("员工推送")
            # r = TASKS.DoChangeWorkMessage.apply_async((place.id, data))
            return Response({"rescode": 200, "resmsg": "false"})
        elif data.get("message_type") == "apartment":  # 新1.2门店信息推送
            # print("门店推送")
            # r = TASKS.DoChangeWorkMessage.apply_async((place.id, data))
            return Response({"rescode": 200, "resmsg": "false"})
        elif data.get("message_type") == "server":  # 新1.1 收银端上线通知
            # print("收银端上线通知")
            # r = TASKS.DoChangeWorkMessage.apply_async((place.id, data))
            return Response({"rescode": 200, "resmsg": "false"})
        else:
            return Response({"rescode": 400, "resmsg": "未识别的请求"})


class FsygShopreqsnListViewSet(viewsets.ModelViewSet):
    __title__ = "查询凡商商品订单"
    __group__ = "凡商接口"
    __info__ = {"get": "查询凡商商品订单"}
    __doc__ = """	list:
    <h4>查询凡商商品订单列表</h4>
    retrieve:
    <h4>查询凡商商品订单详情</h4>
    """
    http_method_names = ["get"]
    authentication_classes = [
        MyJWTAuthentication,
        BoxJWTAuthentication,
        WeChatJWTAuthentication,
        BarJWTAuthentication,
    ]
    permission_classes = [
        MyPermissions | BoxPermissions | WeChatPermissions | BarPermissions
    ]
    serializer_class = FsygShopreqsnListSerializer
    queryset = FsygShopreqsnList.objects.all()

    filter_backends = [ListDjangoFilterBackend, SearchFilter]
    filterset_class = FsygShopreqsnListFilterSet
    search_fields = ["reqsn"]

    # def has_Staff_Info(self, sid):
    #     """查询员工信息"""
    #     try:
    #         r = AllinpayStaffList.objects.get(id=sid)
    #     except BaseException as err:
    #         return None
    #     else:
    #         return {"id": r.id, "basename": r.basename, "nicename": r.nicename}

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        # data = serializer.data.copy()
        # for i in range(len(data)):
        #     try:
        #         r = AllinpayCallmeList.objects.get(bem=data[i]["id"])
        #     except BaseException as err:
        #         data[i]["callme"] = None
        #     else:
        #         data[i]["callme"] = {
        #             "id": r.id,
        #             "reqsn": r.reqsn,
        #             "area": r.area,
        #             "source": r.source,
        #             "status": r.status,
        #             "le1": r.le1,
        #             "le1k": r.le1k,
        #             "target": self.has_Staff_Info(r.target),
        #         }
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})


class FsygMemberLoadDataViewSet(viewsets.ModelViewSet):
    __title__ = "查询会员数据"
    __group__ = "凡商接口"
    __info__ = {"post": "处理所有异常会员"}
    __doc__ = """
    create:
    <h4>处理所有异常会员</h4>
    """
    http_method_names = ["post"]
    authentication_classes = (
        []
        if settings.DEBUG
        else [
            MyJWTAuthentication,
        ]
    )
    permission_classes = [AllPermissions] if settings.DEBUG else [MyPermissions]
    serializer_class = NoneSerializer
    queryset = FsygMemberList.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # serializer.save()
        res = self.get_queryset().filter(level__isnull=True).values("wb_id", "codeid")
        for i in res:
            r = TASKS.doRequestProgress.apply_async((i.get("wb_id"), i.get("codeid")))
        return Response({"rescode": 200, "resmsg": "ok"})


class FsygMemberListViewSet(viewsets.ModelViewSet):
    __title__ = "查询会员列表"
    __group__ = "凡商接口"
    __info__ = {"get": "查询会员列表"}
    __doc__ = """	
    list:
    <h4>查询会员列表</h4>
    retrieve:
    <h4>查询会员详情</h4>
    """
    http_method_names = ["get"]
    authentication_classes = [
        MyJWTAuthentication,
    ]

    permission_classes = [MyPermissions]
    serializer_class = FsygMemberListSerializer
    queryset = FsygMemberList.objects.all()

    filter_backends = [ListDjangoFilterBackend]
    filterset_fields = ["wb_id", "level"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})


class FsygMemberLevelViewSet(viewsets.ModelViewSet):
    __title__ = "会员等级对应表"
    __group__ = "凡商接口"
    __info__ = {
        "get": "查询会员等级对应表",
        "post": "创建会员等级对应表",
        "put": "编辑会员等级对应表",
        "delete": "移除会员等级对应表",
    }
    __doc__ = """	list:
    <h4>会员等级对应表列表</h4>
    retrieve:
    <h4>会员等级对应详情</h4>
    create:
    <h4>创建会员等级对应表</h4>
    update:
    <h4>编辑会员等级对应表</h4>
    delete:
    <h4>移除会员等级对应表</h4>"""
    http_method_names = ["get", "post", "put", "delete"]
    authentication_classes = [
        MyJWTAuthentication,
        WeChatJWTAuthentication,
        BarJWTAuthentication,
    ]
    permission_classes = [MyPermissions | WeChatPermissions | BarJWTAuthentication]
    serializer_class = FsygMemberLevelSerializer
    queryset = FsygMemberLevel.objects.all()

    filter_backends = [ListDjangoFilterBackend]
    filterset_fields = ["wbcode"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def update(self, request, *args, **kwargs):
        partial = True
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


# 检查视图
filter_views(globals())
